//
//  KABillDetailModel.swift
//  kano
//
//  Created by Frank on 2024/9/20.
//

import KakaJSON

class KABillDetailSubLoans: Convertible {
    //index
    var index: Int = 0
    //leftAmount  贷款金额
    var leftAmount: Double = 0.00
    //loanLeftAmount 待还金额
    var loanLeftAmount: Double = 0.00
    //subLoanAmount
    var subLoanAmount: Double = 0.00
    //overdueFee 逾期手续费
    var overdueFee: Double = 0.00
    //fee 手续费
    var fee: Double = 0.00
    //repaymentAmount 还款金额
    var repaymentAmount: Double = 0.00
    //repaymentTime 还款时间
    var repaymentTime: TimeInterval = 0
    //dueTime 过期日期
    var dueTime: TimeInterval = 0
    //exceedDays 过期多少天
    var exceedDays: Int = 0
    //repaymentStatus
    var repaymentStatus: Int = 0
    //还款详情页，手动选择账单时用于标识选中状态
    var select: Bool = false
    
    //gid
    var gid: String = ""
    //subRate
    var subRate: Double = 0.00

    required init() {}
    init(index: Int, gid: String = "", leftAmount: Double, loanLeftAmount: Double, subLoanAmount: Double, overdueFee: Double, fee: Double, subRate: Double = 0.00, repaymentAmount: Double, repaymentTime: TimeInterval = 0, dueTime: TimeInterval, exceedDays: Int, repaymentStatus: Int, select: Bool = false) {
        self.index = index
        self.gid = gid
        self.leftAmount = leftAmount
        self.loanLeftAmount = loanLeftAmount
        self.subLoanAmount = subLoanAmount
        self.overdueFee = overdueFee
        self.fee = fee
        self.subRate = subRate
        self.repaymentAmount = repaymentAmount
        self.repaymentTime = repaymentTime
        self.dueTime = dueTime
        self.exceedDays = exceedDays
        self.repaymentStatus = repaymentStatus
        self.select = select
    }
}

class KAReduceResult: Convertible {
    //loanGid
    var loanGid: String = ""
    //shouldShow
    var shouldShow: Bool = false
    //beforeOverDueFee
    var beforeOverDueFee: Int = 0
    //reduceFee
    var reduceFee: Int = 0
    required init() {}
}

class KABillDetailModel: Convertible {
    //借款协议中，展示分期还款日期（自定义字段）
    var dueDateArr: [TimeInterval] = []
    // creditAddress 授信地址（借款协议用）
    var creditAddress: String = ""
    //userName 用户名（借款协议用）
    var userName: String = ""
    //贷款金额 loanAmount
    var loanAmount : Double = 0.00
    //fee 手续费
    var fee : Double = 0.00
    //interest 利息
    var interest : Double = 0.00
    //overdueFee 逾期费用
    var overdueFee: Double = 0.00
    //repaymentAmount 还款金额
    var repaymentAmount : Double = 0.00
    //loanLeftAmount 待还金额
    var loanLeftAmount: Double = 0.00
    //loanStatus 0: 借款失败 1:已还款 2:还款失败 3:打款中 4: 待还款 5:已逾期 8:借款成功，等待打款 9:审核中
    var loanStatus: Int = 0
    //dueTime 过期日期
    var dueTime: TimeInterval = 0
    //exceedDays 过期天数
    var exceedDays: Int = 0
    //loanTime 贷款时间
    var loanTime : TimeInterval = 0
    //loanType 贷款类型
    var loanType: Int = 0
    //subLoanCount 分期数量
    var subLoanCount: Int = 0
    //withdrawCardNo 银行卡号
    var withdrawCardNo: String = ""
    //orderNo 账单
    var orderNo: String = ""
    //loanPeriod 贷款天数
    var loanPeriod: Int = 0
    //status  0：打款中，2：还款处理中--7/20续期中，9：审核中, 8：因网络原因借款失败 99：因没有获取到绑卡token而借款失败,   1、4 ：待还款
    var status: Int = 0
    //subLoans 大额分期账单，蝌蚪贷手动拆分订单
    var subLoans : [KABillDetailSubLoans]?
    //repaymentVouchers 还款凭证，还没用上
    var repaymentVouchers : [KABillDetailSubLoans]?
    //tadpoleLoanFlag 是否是蝌蚪贷订单
    var tadpoleLoanFlag: Bool = false
    //tadpoleLoanLeftAmount 蝌蚪贷 待还金额
    var tadpoleLoanLeftAmount: Double = 0.00
    //eachPeriod 蝌蚪贷"14|346"数据分离
    var eachPeriod: String = ""
    //repayRatio 蝌蚪贷每期利率
    var repayRatio: String = ""
    //拆分蝌蚪贷时间时手动记录，用于逾期账单计算利息使用
    var firstPeriod: Int = 0
    
    var reductionFee: Int = 0
    var reduceResult: [KAReduceResult]?
    var invalidTime: TimeInterval = 0
    var processingAmount: Int = 0
    var currentTime: TimeInterval = 0
    var renewExpiredTime: TimeInterval = 0
    var renewRepaidCapital: String = ""
    var renewFee: String = ""
    var renewAmount: Int = 0
    var renewable: Bool = false
    var refundingStatus: Int = 0
    var repayStatus: Int = 0
    var productId: Int = 0
    var channelType: Int = 0
    var repaymentSuccessCount: Int = 0
    var lastRepaymentFailedTime: TimeInterval = 0
    var repaymentFailedCount: Int = 0
    var haveRepaymentInProcess : Int = 0
    var transactionTime: TimeInterval = 0
    var tax: Int = 0
    var netAmount: Int = 0
    
    
    required init() {}
    
    func kj_didConvertToModel(from json: [String : Any]) {
        if tadpoleLoanFlag {
            //手动分成两期
            subLoanCount = 2
            loanPeriod = 360
            
            //"14|346"数据分离
            let eachPeriodArray = eachPeriod.components(separatedBy: "|")
            let repayRatioArray = repayRatio.components(separatedBy: "|")
            //string to int
            let splitPeriod = eachPeriodArray.compactMap { Int($0) }
            let splitRatio = repayRatioArray.compactMap { Double($0) }
            
            //如果tadpoleLoanLeftAmount有值直接用，没值手动计算
            var leftAmount = tadpoleLoanLeftAmount != 0 ? Double(tadpoleLoanLeftAmount) : (Double(loanAmount) * splitRatio[0])
            
            firstPeriod = splitPeriod[0]
            //计算蝌蚪贷分期
            var list: [KABillDetailSubLoans] = []
            list.append(KABillDetailSubLoans(index: 1,
                                             leftAmount: Double(Int(leftAmount)),
                                             loanLeftAmount: Double(leftAmount),
                                             subLoanAmount: Double(leftAmount) - fee,
                                             overdueFee: overdueFee,
                                             fee: fee,
                                             repaymentAmount: loanStatus == 1 ? Double(leftAmount) : repaymentAmount,
                                             dueTime: loanTime + TimeInterval((splitPeriod[0]-1) * 86400),
                                             exceedDays: exceedDays,
                                             repaymentStatus: loanStatus == 1 ? 3 : 1
                                            ))
            
            leftAmount = Double(loanAmount) * splitRatio[1]
            let days = splitPeriod[0] + splitPeriod[1] - 1
            list.append(KABillDetailSubLoans(index: 2,
                                             leftAmount: Double(leftAmount),
                                             loanLeftAmount: Double(leftAmount),
                                             subLoanAmount: Double(leftAmount),
                                             overdueFee: overdueFee,
                                             fee: fee,
                                             repaymentAmount: loanStatus == 1 ? Double(leftAmount) : repaymentAmount,
                                             dueTime: loanTime + TimeInterval(days * 86400),
                                             exceedDays: -1,
                                             repaymentStatus: loanStatus == 1 ? 3 : 1
                                            ))
            
            subLoans = list
        }
    }
    
    func ka_getDueDate() -> [TimeInterval] {
        //大额、蝌蚪贷
        if subLoanCount > 0 {
            let dueTime = subLoans!.map { $0.dueTime }
            return dueTime
        }
        else {
            return [dueTime]
        }
    }
    
    func ka_overDays() -> Int {
        if subLoanCount > 0 && !tadpoleLoanFlag {
            for subLoan in subLoans! {
                if subLoan.repaymentStatus != 3 {
                    return subLoan.exceedDays
                }
            }
            return 0
        } else {
            return exceedDays
        }
    }
    
    //是否逾期
    func ka_hasOverDueBill() -> Bool {
        //大额，1、遍历找到未还清款账单 2、判断该账单是否已逾期
        if subLoanCount > 0 && !tadpoleLoanFlag {
            for subLoan in subLoans! {
                if subLoan.repaymentStatus != 3 {
                    return subLoan.exceedDays > 0
                }
            }
            return false
        }
        //蝌蚪贷、小额，直接用外部逾期天数判断即可
        else {
            return exceedDays > 0
        }
    }
    
    func ka_isDueTodayUnpay() -> Bool {
        if subLoanCount > 0 && !tadpoleLoanFlag {
            for subLoan in subLoans! {
                if subLoan.repaymentStatus != 3 {
                    return subLoan.exceedDays == 0 && subLoan.repaymentStatus != 3
                }
            }
            return false
        } else {
            return exceedDays == 0 && loanStatus != 1
        }
    }
}

